/*
 @name: cloud.js
 @description: 云端素材列表js - 这块是从在线版 素材中心 移植过来的
 @require: vue.js,client-api
 @date: 2015/9/2
 @author: Nero(Nero@Nero-zou.com)
 */
var MATERIAL_SERVER_BASE=window.opener.SITE_URL+'/';
var MaterialService=window.opener.MaterialService;
var currentAccount=window.opener.wxb.currentAccount;
var selectedWrap=window.opener.getWrap('material');

var utils = {
    showLoading: function (target) {
        var oldHtml = target.html();
        target.addClass('js-loading disabled');
        var fa = target.find('i.fa');
        if (fa.length == 0) {
            try {
                target.prepend('<i class="fa fa-spinner fa-loading"></i> ');
            } catch (e) {

            }
        } else {
            fa.attr('class', 'fa fa-spinner fa-loading');
        }
        return {
            revert: function () {
                target.html(oldHtml);
                target.removeClass('js-loading disabled');
            }
        };
    }
};
var cloudList = new Vue({
    el: '#cloudMaterial',
    data: {
        list_article: [],//文章模式 数据
        list_material: [],//素材模式 数据
        list_material_heights:{
            col1:1,//第一列的高度 递增是为了 方便计算高度， 同高度时 优先放到 第一列
            col2:2,//第二列的高度
            col3:3//第三列的高度
        },
        loadingMaterial:false,//是否 正在加载 素材数据
        pager:{
            firstRecord: 0,
            lastRecord: 0,
            numPages: 0,
            numRecords: 0,
            page: 1,
            perPage: 3
        },//分页数据
        param: {
            authorizer_id: "all",//加载哪个公众号的素材
            page: 1,
            show: 0,// 0 => 素材模式 ， 1 => 文章模式
            status: 0 //0-全部 、 1-已同步、 2-未同步
        }
    },
    methods: {
        //获取最矮的列 - 素材模式
        getMinHeightCol:function(){
            var max=Infinity;
            var result='';
            for (var col in this.list_material_heights) {
                if(this.list_material_heights[col]<max){
                    max=this.list_material_heights[col];
                    result=col;
                }
            }
            return result;
        },
        /**
         * 根据页面状态 加载数据
         * @param [loadConfig] - 带上参数 -- 文章模式目前没用
         */
        loadRightData: function (loadConfig) {
            var _this=this;
            loadConfig=loadConfig?loadConfig:{};
            var config = $.extend(true,{},this.param,loadConfig);
            var tempData;
            if (config.append !== true) {
                tempData = [];
                if (config.show == 0) {
                    this.list_material_heights.col1=1;
                    this.list_material_heights.col2=2;
                    this.list_material_heights.col3=3;
                    this.list_material=[];
                } else {
                    this.list_article=[];
                }
            }else{
                if (config.show == 0) {
                    tempData=this.list_material;
                } else {
                    tempData=this.list_article;
                }
            }
            if(config.authorizer_id=='all'){
                config.authorizer_id='';
            }
            if(config.status==0){
                config.status="";
            }else if(config.status==2){
                config.status=0;
            }
            delete config.append;

            _this.loadingMaterial=true;
            $.getJSON(MATERIAL_SERVER_BASE+'client/news/list', config, function (response) {
                _this.loadingMaterial=false;
                if (response.error != 0) {
                    toastr.error(response.message, "未能获取到素材");
                    return;
                }


                if (config.show == 0) {
                    //素材模式
                    for (var i = 0, max = response.data.length; i < max; i++) {
                        var data_i = response.data[i];
                        var this_height=170+78*data_i.articles.length;
                        var col=_this.getMinHeightCol();
                        data_i.col=col;
                        data_i.height=this_height;
                        data_i.loading=false;
                        _this.list_material_heights[col]+=this_height;
                        tempData.push(data_i);
                    }
                    _this.list_material=tempData;
                } else {
                    //文章模式
                    for (var i = 0, max = response.data.length; i < max; i++) {
                        var data_i = response.data[i];
                        var accounts=data_i.sync_authorizer;
                        accounts=accounts?accounts:[];
                        for (var j = 0; j < accounts.length; j++) {
                            var obj = accounts[j];
                            if(obj==null){
                                continue;
                            }
                            if(j<3){
                                obj.show=true;
                            }else{
                                obj.show=false;
                            }
                        }
                        data_i.recordsOpen=false;
                        tempData.push(data_i);
                    }
                    _this.list_article=tempData;
                }
                _this.pager=response.pager;
            }).error(function(error){
                _this.loadingMaterial=false;
                toastr.error(error.responseText,'加载素材数据失败');
            });
        },
        loadMore:function(){
            this.param.page=this.pager.page+1;
            this.loadRightData({append:true});
        },
        downloadMaterial:function(material){
            var materialCloudId=material.id;
            material.loading=true;
            LoginWXB.materialCloudGetDetail(materialCloudId).then(function(response){
                material.loading=false;
                var newMaterial = {
                    cloudId: materialCloudId,
                    data: []
                };

                for (var i = 0; i < response.data.length; i++) {
                    var obj = response.data[i];
                    var temp={
                        author: obj.author,
                        content: obj.content,
                        digest: obj.digest,
                        fileid: obj.fileid,
                        id: obj.id,
                        article_id: obj.id,//云端的 文章id，修改素材
                        show_cover_pic: obj.show_cover_pic,
                        sourceurl: obj.sourceurl,
                        title: obj.title,
                        wxFileId: "",
                        wxbCoverPath: obj.thumb_image,
                        add_footer: obj.add_footer,
                        add_guide: obj.add_guide,
                        add_header: obj.add_header,
                    };
                    for (var key in temp) {
                        if(!temp[key]){
                            temp[key]='';
                        }
                    }
                    temp.title=temp.title.replace(/&nbsp;/gim,' ');
                    newMaterial.data.push(temp);
                }

                MaterialService.add(currentAccount,newMaterial).then(function (newId) {
                    if (currentAccount != "") {
                        selectedWrap.find(".account-list>li[data-wxid=" + currentAccount + "]").trigger("click");
                    } else {
                        selectedWrap.find(".account-list>li:eq(1)").trigger("click");
                    }
                    window.close();

                }).catch(function (e) {
                    toastr.error(e,"保存素材失败");
                    console.log(e);
                });
            }).catch(function(err){
                material.loading=false;
                toastr.error(err,"获取云端素材失败");

            })
            return
            $.getJSON(MATERIAL_SERVER_BASE+'client/news/detail/'+material.id, function (response) {
                material.loading=false;
                if (response.error == 0) {
                    var newMaterial = {
                        cloudId: response.data.id,
                        data: []
                    };

                    for (var i = 0; i < response.data.articles.length; i++) {
                        var obj = response.data.articles[i];
                        var temp={
                            author: obj.author,
                            content: obj.content,
                            digest: obj.digest,
                            fetchUrl: "",
                            fileid: obj.full_thumb_image,
                            id: obj.id,
                            article_id: obj.id,//云端的 文章id，修改素材
                            show_cover_pic: obj.show_cover_pic,
                            sourceurl: obj.content_source_url,
                            title: obj.title,
                            wxFileId: "",
                            wxbCoverPath: obj.thumb_image,
                        };
                        for (var key in temp) {
                            if(!temp[key]){
                                temp[key]='';
                            }
                        }
                        temp.title=temp.title.replace(/&nbsp;/gim,' ');
                        newMaterial.data.push(temp);
                    }

                    MaterialService.add(currentAccount,newMaterial).then(function (newId) {
                        if (currentAccount != "") {
                            selectedWrap.find(".account-list>li[data-wxid=" + currentAccount + "]").trigger("click");
                        } else {
                            selectedWrap.find(".account-list>li:eq(1)").trigger("click");
                        }
                        window.close();

                    }).catch(function (e) {
                        toastr.error(e,"保存素材失败");
                        console.log(e);
                    });

                }else{
                    toastr.error('服务器繁忙，请稍后再试！',"获取云端素材失败");
                }
            });
        },
        deleteMaterial:function(material){
            var _this=this;
            var win=Win.confirm({
                content:'是否删除这个云端素材（ID：'+material.id+'）？',
                yesFunc:function(){
                    var btn=win.find('._model-sure-btn');
                    var loading=utils.showLoading(btn);
                    $.ajax({
                        url: MATERIAL_SERVER_BASE+'client/news/delete',
                        type: 'post',
                        data: {id:material.id},
                        dataType: 'json',
                        success: function (response) {
                            win.modal('hide');
                            if (response.error == 0) {
                                toastr.success('', '删除成功！');
                                for (var i = 0; i < _this.list_material.length; i++) {
                                    var material_i = _this.list_material[i];
                                    if(material_i.id==material.id){
                                        _this.list_material.splice(i,1);
                                        var col=material_i.col;
                                        var height=material_i.height;
                                        _this.list_material_heights[col]-=height;//删除后 更新 每列的高度
                                        return;
                                    }
                                }
                            } else {
                                toastr.error(response.message, '删除失败！');
                            }
                        },
                        error: function (error) {
                            win.modal('hide');
                            toastr.error(error.responseText, '删除失败！');
                        }
                    });
                    return false;
                }
            });
        }
    }
});

function init() {
    cloudList.loadRightData();
}